<template>
  <div class="forget-container">
    <el-card class="forget-card">
      <template #header>
        <span>找回用户名或密码</span>
      </template>

      <div v-if="sent">
        <p>
          重置链接已发送至邮箱 <strong>{{ form.email }}</strong
          >，请前往邮箱查看。
        </p>
      </div>

      <el-form v-else :model="form" label-width="100px" @submit.prevent="handleSend">
        <el-form-item label="注册邮箱">
          <el-input v-model="form.email" placeholder="请输入注册邮箱" />
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" native-type="submit" type="primary">
            发送重置邮件
          </el-button>
          <el-button @click="goToLogin">返回登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/authStore.ts'
import router from '@/router'

const authStore = useAuthStore()
const goToLogin = () => {
  router.push('/login')
}

const form = reactive({
  email: '',
})
const loading = ref(false)
const sent = ref(false)

const handleSend = async () => {
  if (!form.email) {
    ElMessage.warning('请输入邮箱')
    return
  }
  loading.value = true
  try {
    await authStore.findAccounts(form.email)
    ElMessage.success('重置链接已发送至您的邮箱')
    sent.value = true
  } catch (error) {
    ElMessage.error('发送失败，请确认邮箱是否正确')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.forget-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.forget-card {
  width: 450px;
}
</style>
